const express = require('express');
const router = express.Router();
const Resource = require('../models/Resource');
const auth = require('../middleware/auth');
const mongoose = require('mongoose');
const multer = require('multer');
const path = require('path');
const fs = require('fs');

// 配置文件上传
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    const uploadDir = path.join(__dirname, '../public/uploads/checkins');
    if (!fs.existsSync(uploadDir)) {
      fs.mkdirSync(uploadDir, { recursive: true });
    }
    cb(null, uploadDir);
  },
  filename: function (req, file, cb) {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    cb(null, uniqueSuffix + path.extname(file.originalname));
  }
});

const upload = multer({ storage: storage });

// 获取所有资源
router.get('/', async (req, res) => {
  try {
    console.log('收到获取资源请求');
    
    // 添加查询条件日志
    console.log('查询条件:', { status: 'active' });
    
    const resources = await Resource.find({ status: 'active' });
    
    // 添加详细的资源日志
    console.log('查询结果:', {
      count: resources.length,
      resourceTypes: resources.map(r => r.type),
      titles: resources.map(r => r.title)
    });

    res.json(resources);
  } catch (error) {
    console.error('获取资源列表失败:', error);
    res.status(500).json({ message: '获取资源列表失败' });
  }
});

// 按类型获取资源
router.get('/type/:type', async (req, res) => {
  try {
    const resources = await Resource.find({ 
      type: req.params.type,
      status: 'active'
    });
    res.json(resources);
  } catch (error) {
    console.error('获取资源列表失败:', error);
    res.status(500).json({ message: '获取资源列表失败' });
  }
});

// 获取单个资源详情
router.get('/:id', async (req, res) => {
  try {
    const resource = await Resource.findById(req.params.id);
    if (!resource) {
      return res.status(404).json({ message: '资源不存在' });
    }
    res.json(resource);
  } catch (error) {
    console.error('获取资源详情失败:', error);
    res.status(500).json({ message: '获取资源详情失败' });
  }
});

// 参与活动
router.post('/:id/join', auth, async (req, res) => {
  try {
    const resource = await Resource.findById(req.params.id);
    if (!resource) {
      return res.status(404).json({ message: '活动不存在' });
    }

    // 检查是否已经参与
    if (resource.participants.some(p => p.userId.toString() === req.userId)) {
      return res.status(400).json({ message: '已经参与该活动' });
    }

    // 添加参与记录
    resource.participants.push({
      userId: req.userId,
      joinedAt: new Date(),
      status: '进行中',
      checkins: []
    });

    await resource.save();
    res.json({ message: '成功参与活动' });
  } catch (error) {
    console.error('参与活动失败:', error);
    res.status(500).json({ message: '参与活动失败' });
  }
});

// 活动打卡
router.post('/:id/checkin', auth, upload.array('images', 5), async (req, res) => {
  try {
    const resourceId = req.params.id;
    const { note, location } = req.body;
    
    console.log('收到打卡请求:', {
      resourceId,
      userId: req.userId,
      note: note ? '有笔记' : '无笔记',
      location: location ? '有位置' : '无位置',
      files: req.files ? req.files.length : 0
    });
    
    // 处理示例活动的特殊情况
    if (resourceId === '1' || resourceId === '2') {
      console.log('检测到示例活动打卡请求，返回模拟成功响应');
      
      // 处理图片上传
      let imageUrls = [];
      if (req.files && req.files.length > 0) {
        imageUrls = req.files.map(file => `/uploads/checkins/${file.filename}`);
      }
      
      // 直接返回成功响应，不创建真实活动
      return res.status(201).json({
        message: '打卡成功',
        checkin: {
          date: new Date(),
          note: note || '',
          images: imageUrls,
          location: [0, 0]
        },
        progress: resourceId === '1' ? 20 : 3.33, // 模拟进度
        resourceId: resourceId
      });
    }
    
    // 查找资源
    const resource = await Resource.findById(resourceId);
    if (!resource) {
      console.log('打卡失败: 活动不存在');
      return res.status(404).json({ message: '活动不存在' });
    }
    
    // 验证位置信息 - 如果没有位置信息，使用默认位置
    let locationData = [0, 0]; // 默认位置
    if (location) {
      try {
        locationData = JSON.parse(location);
        if (!Array.isArray(locationData) || locationData.length !== 2) {
          locationData = [0, 0]; // 使用默认位置
        }
      } catch (error) {
        console.log('位置信息解析失败，使用默认位置');
        // 使用默认位置，不返回错误
      }
    }
    
    // 查找用户参与记录
    const participantIndex = resource.participants.findIndex(
      p => p.userId.toString() === req.userId.toString()
    );
    
    // 如果用户未参与，自动添加参与记录
    if (participantIndex === -1) {
      console.log('用户未参与活动，自动添加参与记录');
      resource.participants.push({
        userId: req.userId,
        joinedAt: new Date(),
        status: '进行中',
        checkins: []
      });
      
      // 重新获取参与者索引
      const newParticipantIndex = resource.participants.length - 1;
      
      // 处理图片上传
      let imageUrls = [];
      if (req.files && req.files.length > 0) {
        imageUrls = req.files.map(file => `/uploads/checkins/${file.filename}`);
      }
      
      // 添加打卡记录
      const checkin = {
        date: new Date(),
        location: locationData,
        note: note || '',
        images: imageUrls
      };
      
      resource.participants[newParticipantIndex].checkins.push(checkin);
      
      // 检查是否完成所有打卡
      if (resource.participants[newParticipantIndex].checkins.length >= resource.checkInRequired) {
        resource.participants[newParticipantIndex].status = '已完成';
      }
      
      await resource.save();
      
      console.log('打卡成功 (新参与者)');
      return res.status(201).json({
        message: '打卡成功',
        checkin,
        progress: (resource.participants[newParticipantIndex].checkins.length / resource.checkInRequired) * 100
      });
    }
    
    // 处理图片上传
    let imageUrls = [];
    if (req.files && req.files.length > 0) {
      imageUrls = req.files.map(file => `/uploads/checkins/${file.filename}`);
    }
    
    // 添加打卡记录
    const checkin = {
      date: new Date(),
      location: locationData,
      note: note || '',
      images: imageUrls
    };
    
    resource.participants[participantIndex].checkins.push(checkin);
    
    // 检查是否完成所有打卡
    if (resource.participants[participantIndex].checkins.length >= resource.checkInRequired) {
      resource.participants[participantIndex].status = '已完成';
    }
    
    await resource.save();
    
    console.log('打卡成功');
    res.status(201).json({
      message: '打卡成功',
      checkin,
      progress: (resource.participants[participantIndex].checkins.length / resource.checkInRequired) * 100
    });
  } catch (error) {
    console.error('打卡失败:', error);
    res.status(500).json({ message: '打卡失败，请稍后重试' });
  }
});

// 获取用户参与的活动
router.get('/user/activities', auth, async (req, res) => {
  try {
    console.log('获取用户活动请求, userId:', req.userId);
    
    // 确保 userId 存在且格式正确
    if (!req.userId) {
      return res.status(400).json({ message: '未找到用户ID' });
    }

    // 尝试不同的查询方式
    let resources = await Resource.find({
      'participants.userId': new mongoose.Types.ObjectId(req.userId),
      type: '活动'
    });

    // 如果没有找到活动，尝试使用字符串比较
    if (resources.length === 0) {
      resources = await Resource.find({
        type: '活动'
      });
      
      // 手动过滤参与者
      resources = resources.filter(resource => 
        resource.participants.some(p => p.userId.toString() === req.userId.toString())
      );
    }

    console.log('找到的活动数量:', resources.length);

    // 如果仍然没有找到活动，返回一些示例活动
    if (resources.length === 0) {
      // 检查数据库中是否有任何活动
      const allActivities = await Resource.find({ type: '活动' });
      console.log('数据库中的所有活动数量:', allActivities.length);
      
      if (allActivities.length > 0) {
        // 如果有活动但用户没有参与，返回一些示例活动
        return res.json([
          {
            _id: '1',
            title: '植树活动',
            description: '参与社区植树活动，为环境贡献一份力量。',
            progress: 0,
            remainingDays: 30,
            status: '未参与',
            type: '活动',
            startDate: new Date(),
            endDate: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000),
            checkInRequired: 5,
            checkins: []
          },
          {
            _id: '2',
            title: '垃圾分类挑战',
            description: '连续30天正确进行垃圾分类，培养环保习惯。',
            progress: 0,
            remainingDays: 30,
            status: '未参与',
            type: '活动',
            startDate: new Date(),
            endDate: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000),
            checkInRequired: 30,
            checkins: []
          }
        ]);
      }
    }

    const activities = resources.map(resource => {
      const participant = resource.participants.find(p => 
        p.userId.toString() === req.userId.toString()
      );

      // 如果找不到参与记录，创建一个默认的
      const defaultParticipant = {
        status: '未参与',
        joinedAt: new Date(),
        checkins: []
      };

      const actualParticipant = participant || defaultParticipant;

      return {
        _id: resource._id,
        title: resource.title,
        description: resource.description,
        type: resource.type,
        status: actualParticipant.status,
        joinedAt: actualParticipant.joinedAt,
        progress: resource.checkInRequired > 0 
          ? (actualParticipant.checkins?.length || 0) / resource.checkInRequired * 100 
          : 100,
        checkins: actualParticipant.checkins || [],
        checkInRequired: resource.checkInRequired,
        startDate: resource.startDate,
        endDate: resource.endDate,
        remainingDays: Math.max(0, Math.ceil(
          (new Date(resource.endDate) - new Date()) / (1000 * 60 * 60 * 24)
        ))
      };
    });

    console.log('返回处理后的活动:', activities);
    res.json(activities);
  } catch (error) {
    console.error('获取用户活动失败:', error);
    res.status(500).json({ message: '获取用户活动失败' });
  }
});

module.exports = router; 